import { Radio } from 'antd';
import { DatePicker } from 'antd-mobile';
import { Link, RouteComponentProps } from 'dva/router';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { WxDoctorApi } from '../../../api';
import { IDoctorMsg, INotiItem, INotiListReq } from '../../../api/WxDoctorApi';
import { MobileHeader, MobileNoDatas } from '../../../components';
import { UpdateTitle } from '../../../utils';

import { MobilePagination } from '../../../utils';
import './PatientMsg.scss';

interface IPatientMsgProps extends RouteComponentProps<{ id: string }> {}
export function PatientMsg(props: IPatientMsgProps) {
  const [startDate, setStartDate] = useState();
  const [endDate, setEndDate] = useState();
  const [curType, setCurType] = useState(1);
  const [patientMsg, setPatientMsg] = useState({} as IDoctorMsg);

  const [total, setTotal] = useState();
  const [notiDatas, setNotiDatas] = useState([] as INotiItem[]);
  // tslint:disable-next-line:no-any
  let notifyData: any[] | never[] = [];

  let page = { pageSize: 10, total: 0, current: 1 };

  useEffect(() => {
    getPatientMsg();
    UpdateTitle('患者信息');
    window.addEventListener('scroll', scrollE, true);
    return () => {
      window.removeEventListener('scroll', scrollE, true);
    };
  }, []);

  /**
   *  筛选 通知类型点击事件
   */
  useEffect(() => {
    setNotiDatas([]);
    getNotiList();
  }, [curType]);

  /**
   *  根据时间 刷新列表
   */
  useEffect(() => {
    if (startDate && endDate) {
      getNotiList();
    }
  }, [startDate, endDate]);
  function scrollE() {
    MobilePagination('PatientNotifyMsg', page.current, page.pageSize, page.total).then(pageNum => {
      if (pageNum) {
        page.current = pageNum;
        getNotiList();
      }
    });
  }

  /**
   * 获取病人信息
   */
  async function getPatientMsg() {
    const { result } = await WxDoctorApi.getPatientMsg(props.match.params.id);
    if (result) {
      //
      setPatientMsg(result);
    }
  }

  /**
   * 通知列表
   */

  async function getNotiList() {
    const typeKey = ['', 'FOLLOW_UP_MSG', 'FOLLOW_UP_QUESTIONNAIRE'];
    const notiReq = {
      receiveUserId: props.match.params.id,
      pageSize: page.pageSize,
      pageNum: page.current,
      sysMsgType: typeKey[curType - 1],
    } as INotiListReq;
    if (startDate && endDate) {
      notiReq.startTime = moment(startDate)
        .startOf('day')
        .valueOf();
      notiReq.endTime = moment(endDate)
        .endOf('day')
        .valueOf();
    }
    const { result } = await WxDoctorApi.getPatientNotis(notiReq);
    if (result) {
      page = { current: result.current, total: result.total, pageSize: result.size };
      setTotal(result.total);
      setNotiDatas([...notifyData, ...result.records]);
      notifyData = [...notifyData, ...result.records];
    }
  }

  /**
   * 组 标签
   */
  const groupTag =
    patientMsg &&
    patientMsg.groupNames &&
    patientMsg.groupNames.map((e, index) => {
      return (
        <div key={index} className="groupTag">
          {e}
        </div>
      );
    });

  /**
   * 列表类型筛选
   */

  function notiTypeClick(index: number) {
    setCurType(index);
  }

  /**
   * 列表点击事件
   */

  function itemOnClick(e: INotiItem) {
    props.history.push(`/Doctor/NotiDetail/${e.id}`);
  }

  /**
   * 随访 修改就诊状态
   */
  async function updateItemTreateStatus(item: INotiItem, visitResult: string) {
    const { result } = await WxDoctorApi.updateNotiTreateStatus({ id: item.msgId, visitResult: '1' });
    if (result) {
      //
    }
  }
  /**
   * 病人信息
   */
  const msgCard = (
    <div className="patientMsgCard">
      <img src={patientMsg.headimgurl} className="portrait" />
      <div className="pmsg">
        <div className="msgRow">
          <div className="nameRow">
            <span className="name"> {patientMsg.name} </span>
            <span className="sex"> {patientMsg.gender ? '男' : '女'} </span> <span>{patientMsg.age} 岁 </span>
          </div>
          <Link to={`/Doctor/EditPatient/${props.match.params.id}`}>
            <div className="editAction">编辑 </div>
          </Link>
        </div>
        <div className="codeContainer">
          <div className="codeRow">
            就诊编号: <span className="number"> {patientMsg.sampleSequence}</span>
          </div>
        </div>
        <div className="discription" hidden={true}>
          此处是备注信息,有则显示,没有不显示.默认是没有的哦
        </div>
        <div className="taskMarkIcons"> {groupTag}</div>
      </div>
    </div>
  );

  /**
   * 日期选择
   */

  const dateSelected = (
    <div className="timerPickerContainer">
      <div>
        <DatePicker
          mode="date"
          value={startDate}
          // tslint:disable-next-line:jsx-no-multiline-js
          onChange={date => {
            setStartDate(date);
          }}
        >
          <div className="timerShow"> {startDate ? moment(startDate).format('YYYY-MM-DD') : '开始时间'}</div>
        </DatePicker>
      </div>
      <div className="spaceLiner">~</div>
      <div>
        <DatePicker
          mode="date"
          value={endDate}
          // tslint:disable-next-line:jsx-no-multiline-js
          onChange={date => {
            setEndDate(date);
          }}
        >
          <div className="timerShow"> {endDate ? moment(endDate).format('YYYY-MM-DD') : '结束时间'}</div>
        </DatePicker>
      </div>
    </div>
  );
  /**
   * list Item
   */
  const renderItems = notiDatas.map((e, index) => {
    const notiType = ['复诊通知', '随访通知', ' 随访问卷'];
    const notiTypeCss = ['notiReVisiting', 'notiVisit', 'questionnaire'];
    const actionTitle = ['患者未操作', '患者已接受', '患者拒绝'];
    const cssTitle = ['noAction', 'accept', 'reject'];
    const notiActionStatus = e.status === 3 ? e.result : 0; // 消息-发送结果 0 未推送 1 未读 2 已读 3 已处理 当处理后就应当 判断处理状态
    const notiStatusTitle = ['未推送', '患者未读', '', ''];
    return (
      <div
        key={index}
        className="notiItemContainer"
        // tslint:disable-next-line:jsx-no-multiline-js
        onClick={() => {
          itemOnClick(e);
        }}
      >
        <div className="titleRow">
          <div className="titleMsg"> {e.title} </div>
          <div className="time"> {moment(e.sendTime).format('YYYY-MM-DD')}</div>
        </div>
        <div className="typesRow">
          <div className="typeLabel">
            {/* tslint:disable-next-line:jsx-no-multiline-js */}
            {curType === 1 && <div className={notiTypeCss[e.sysMsgType - 1]}>{notiType[e.sysMsgType - 1]}</div>}

            <div className={cssTitle[notiActionStatus]}>
              {e.sysMsgType === 3 && e.answerResult === 1 ? '患者已填写' : actionTitle[notiActionStatus]}
            </div>
          </div>
          <div className="iconRow">
            <span className="notReaded">{notiStatusTitle[e.status]}</span>
            <img src={require('../../../assets/moblieImg/icon_more2.svg')} className="moreIcon" />
          </div>
        </div>
      </div>
    );
  });

  const renderVisitItems = notiDatas.map((item, index) => {
    const actionTitle = ['患者未操作', '患者已接受', '患者拒绝'];
    const cssTitle = ['noAction', 'accept', 'reject'];
    const notiActionStatus = item.status === 3 ? item.result : 0; // 消息-发送结果 0 未推送 1 未读 2 已读 3 已处理 当处理后就应当 判断处理状态
    const notiStatusTitle = ['未推送', '患者未读', '', ''];
    return (
      <div key={index} className="notiItemContainer">
        <div
          className="msgContent"
          // tslint:disable-next-line:jsx-no-multiline-js
          onClick={() => {
            itemOnClick(item);
          }}
        >
          <div className="titleRow">
            <div className="titleMsg"> {item.title} </div>
            <div className="time"> {moment(item.sendTime).format('YYYY-MM-DD')}</div>
          </div>
          <div className="typesRow">
            <div className="typeLabel">
              <div className={item.sysMsgType === 1 ? 'notiReVisiting' : 'notiVisit'}>
                {item.sysMsgType === 1 && '复诊'}
                {item.sysMsgType === 2 && '随访'}通知
              </div>
              <div className={cssTitle[notiActionStatus]}> {actionTitle[notiActionStatus]}</div>
            </div>
          </div>
          <div className="visitReQtiemRow">
            <div>
              {item.sysMsgType === 1 && '复诊'}
              {item.sysMsgType === 2 && '随访'}时间: {item.treatmentTime}
            </div>
            <div className="iconRow">
              <span className="notReaded">{notiStatusTitle[item.status]}</span>
              <img src={require('../../../assets/moblieImg/icon_more2.svg')} className="moreIcon" />
            </div>
          </div>
        </div>
        <div hidden={!item.msgId}>
          <Radio.Group
            className="radioGroup"
            defaultValue={'1'}
            // tslint:disable-next-line:jsx-no-multiline-js no-shadowed-variable
            onChange={e => {
              updateItemTreateStatus(item, e.target.value);
              e.stopPropagation();
            }}
          >
            <div style={{ display: 'flex', flex: 1, justifyContent: 'center' }}>
              <Radio value={'1'}>已就诊 </Radio>
            </div>
            <div style={{ display: 'flex', flex: 1, justifyContent: 'center' }}>
              <Radio value="2">未就诊 </Radio>
            </div>
          </Radio.Group>
        </div>
      </div>
    );
  });

  return (
    <div className="PatientMsg" id={'PatientNotifyMsg'}>
      <MobileHeader />
      {msgCard}
      <div className="notiTypeContainer">
        <div style={{ display: 'flex', flex: 3 }}>
          <div onClick={() => notiTypeClick(1)} className={curType === 1 ? 'notiTypeSel' : 'notiType'}>
            通知
          </div>
          <div onClick={() => notiTypeClick(2)} className={curType === 2 ? 'notiTypeSel' : 'notiType'}>
            复诊/随访
          </div>
          <div
            style={{ margin: '0' }}
            onClick={() => notiTypeClick(3)}
            className={curType === 3 ? 'notiTypeSel' : 'notiType'}
          >
            问卷
          </div>
        </div>
        <div className={'total'}> {total}个通知 </div>
      </div>
      <div>{dateSelected} </div>
      <Link to={`/Doctor/AddNotifyType/${props.match.params.id}`}>
        <div className="addNotification">
          <img src={require('../../../assets/moblieImg/btn_add.svg')} className="img" />
          添加通知
        </div>
      </Link>
      <div>
        {(curType === 1 || curType === 3) && renderItems}
        {curType === 2 && renderVisitItems}
      </div>
      <MobileNoDatas show={!notiDatas.length} />
    </div>
  );
}
